package com.z.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.z.admin.entity.User;
import com.z.admin.service.IUserService;
import com.z.admin.vo.UserDto;
import com.z.common.base.PageTableRequest;
import com.z.common.base.ResponseCode;
import com.z.common.base.Results;
import com.z.common.utils.ExportExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jxl.Sheet;
import jxl.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.*;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author z
 * @since 2022-02-13
 */
@Controller
@RequestMapping("/admin/user")
@Api(tags = "用户相关")
public class UserController {

    @Autowired
    private IUserService userService;


    @PreAuthorize("hasAuthority('sys:user')")
    @GetMapping("list")
    @ApiOperation("用户列表分页查询")
    @ResponseBody
    public Results list(PageTableRequest page) {
        page.countOffset();
        Results<User> results = userService.findByPage(page.getOffset(), page.getLimit());
        return results;
    }

    @PreAuthorize("hasAuthority('sys:user')")
    @GetMapping("listByMap")
    @ApiOperation("用户列表分页条件查询")
    @ResponseBody
    public Results listByMap(PageTableRequest page, HttpServletRequest request) {
        page.countOffset();

        Map<String, Object> map = new HashMap<>();
        String username = request.getParameter("admin/username");
        if(!StringUtils.isEmpty(username))
            map.put("admin/username_like_s", username);
        String id = request.getParameter("id");
        if(!StringUtils.isEmpty(id))
            map.put("id_eq_s", id);
        String phone = request.getParameter("phone");
        if(!StringUtils.isEmpty(phone))
            map.put("phone_eq_s", phone);
        Results<User> results = userService.findPageByMap(map, page.getOffset(), page.getLimit());
        return results;
    }

    @PreAuthorize("hasAuthority('sys:user')")
    @GetMapping("toList")
    @ApiOperation("用户列表页面")
    public String toList() {
        return "admin/user/userList";
    }

    @PreAuthorize("hasAuthority('sys:user:add')")
    @ApiOperation("用户添加页面")
    @GetMapping("toAdd")
    public String toAdd(Model model) {
        model.addAttribute("adminUser", new User());
        return "admin/user/userAdd";
    }

    @PreAuthorize("hasAuthority('sys:user:update')")
    @ApiOperation("用户修改页面")
    @GetMapping("toEdit")
    public String toEdit(Model model, String id) {
        if(StringUtils.isEmpty(id)){
            return "参数异常";
        }
        model.addAttribute("adminUser", userService.findById(id));
        return "admin/user/userEdit";
    }

    @PreAuthorize("hasAuthority('sys:user:add')")
    @ApiOperation("用户添加接口")
    @PostMapping("add")
    @ResponseBody
    public Results add(UserDto user, Integer roleId){
        try{
            List<User> userDBs = userService.findUserByPhone(user.getPhone());
            if(userDBs != null && userDBs.size()>0 ){
                throw new Exception("手机号码已存在");
            }
            user.setStatus(1);
            user.setPassword(new BCryptPasswordEncoder().encode("12323"));
            user.setCreateTime(new Date());
            userService.save(user, roleId);
        }catch (Exception e){
            e.printStackTrace();
            return Results.failure(ResponseCode.error.getCode(), e.getMessage());
        }
        return Results.success();
    }

    @PreAuthorize("hasAuthority('sys:user:update')")
    @ApiOperation("用户修改接口")
    @PostMapping("update")
    @ResponseBody
    public Results update(UserDto user, Integer roleId){
        try{
            List<User> userDBs = userService.findUserByPhone(user.getPhone());
            if(userDBs != null && userDBs.size()>0 ){
                for(User userDB : userDBs){
                    if(!(user.getId().equals(userDB.getId()))){
                        throw new Exception("手机号已被占用！");
                    }
                }
            }
            user.setUpdateTime(new Date());
            userService.update(user, roleId);
        }catch (Exception e){
            e.printStackTrace();
            return Results.failure(ResponseCode.error.getCode(), e.getMessage());
        }
        return Results.success();
    }

    @PreAuthorize("hasAuthority('sys:user:del')")
    @ApiOperation("用户删除接口--单个")
    @PostMapping("del")
    @ResponseBody
    public Results del(String id){
        try{
            userService.deleteById(id);
        }catch (Exception e){
            e.printStackTrace();
            return Results.failure(ResponseCode.error.getCode(), e.getMessage());
        }
        return Results.success();
    }

    @PreAuthorize("hasAuthority('sys:user:del')")
    @ApiOperation("用户删除接口--多个")
    @PostMapping("delAll")
    @ResponseBody
    public Results delAll(String ids){
        try{
            for(String id : ids.split(","))
                userService.deleteById(id);
        }catch (Exception e){
            e.printStackTrace();
            return Results.failure(ResponseCode.error.getCode(), e.getMessage());
        }
        return Results.success();
    }

    @PreAuthorize("hasAuthority('sys:user:import')")
    @PostMapping("importExcel")
    @ApiOperation("用户导入接口")
    @ResponseBody
    public Results importExcel(HttpServletRequest request, MultipartFile file) {
        try{
            Workbook readwb = null;
            InputStream instream = file.getInputStream();
            readwb = Workbook.getWorkbook(instream);
            Sheet readsheet = readwb.getSheet(0);
            int rsRows = readsheet.getRows();
            if(rsRows > 0 ){
                List<User> users = new ArrayList<>();
                for (int i = 1; i < rsRows; i++) {
                    //String[] title = { "姓名", "昵称", "电话号", "手机号","子女手机号", "邮箱", "生日(yyyy-mm-dd)",
                    // "性别(1:男 0:女)", "身高(cm)", "体重(kg)",
                    // "胸围(cm)", "腰围(cm)", "臀围(cm)" };
                    String nickname = readsheet.getCell(1, i).getContents();
                    String phone = readsheet.getCell(3, i).getContents();
                    String email = readsheet.getCell(5, i).getContents();

                    QueryWrapper<User> q = new QueryWrapper<>();
                    q.eq("nickname", nickname).or().eq("phone", phone).or().eq("email", email);
                    List<User> userList = userService.getBaseMapper().selectList(q);
                    if(userList != null && userList.size()>0){
                        return Results.failure(ResponseCode.error.getCode(), nickname + "/" + phone + "/" + email + "数据已存在");
                    }
                    users.add(new User(new BCryptPasswordEncoder().encode("12323"), readsheet.getCell(0, i).getContents(), nickname, readsheet.getCell(2, i).getContents(), phone, email)
                    );
                }
                userService.saveBatch(users);
            }
        }catch (Exception e){
            e.printStackTrace();
            return Results.failure(ResponseCode.error.getCode(), e.getMessage());
        }
        return Results.success();
    }

    @PreAuthorize("hasAuthority('sys:user:import')")
    @ApiOperation("用户导入页面")
    @GetMapping("toImport")
    public String toImport() {
        return "admin/user/userImport";
    }
    @PreAuthorize("hasAuthority('sys:user:import')")
    @ApiOperation("用户导入模板下载")
    @GetMapping("/download/module")
    public void download(HttpServletResponse response) {
        try{
            String fileName = "人员导入模板.xls";
            String[] title = { "姓名", "昵称", "电话号", "手机号", "子女手机号", "邮箱", "生日(yyyy-mm-dd)", "性别(1:男 0:女)", "身高(cm)", "体重(kg)", "胸围(cm)", "腰围(cm)", "臀围(cm)" };
            List<String[]> content = new ArrayList<String[]>();
            String[] contentItem = { "张三", "昵称", "6841208", "11111111111", "22222222222", "11111111111@163.com", "1955-08-08", "1", "170", "50", "80", "60", "70" };
            content.add(contentItem);
            ExportExcelUtil.exportExcel(response, fileName, false, 30, 1, 1,
                    title, content);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}